from wtforms import Form,StringField
from wtforms.validators import ValidationError,Email,Length,EqualTo
from models.user import UserModel
from exts import cache

class registerForm(Form):
    email = StringField(validators=[Email(message="请输入正确格式的邮箱")])
    username = StringField(validators=[Length(min=3,max=20,message="请输入正确长度的用户名")])
    password = StringField(validators=[Length(min=3,max=20,message="请输入正确长度的密码")])
    confirm_password = StringField(validators=[EqualTo("password",message="两次密码不一致")])
    captcha = StringField(validators=[Length(min=4,max=4,message="请输入正确长度的验证码")])

    def validate_email(self,field):
        email = field.data
        user = UserModel.query.filter_by(email=email).first()
        if user:
            raise ValidationError("邮箱已存在")

    def validate_captcha(self,field):
        captcha = field.data
        email = self.email.data
        cache_captcha = cache.get(email)
        if not cache_captcha or captcha != captcha:
            raise ValidationError("验证码错误!")


class loginForm(Form):
    email = StringField(validators=[Email(message="请输入正确格式的邮箱")])
    password = StringField(validators=[Length(min=3,max=20,message="请输入正确长度的密码")])


class addEmpForm(Form):
    username = StringField(validators=[Length(min=3,max=20,message="请输入正确长度的用户名")])

    def validate_username(self,field):
        users = UserModel.query.filter_by(is_staff=1).all()
        username = field.data
        for user in users:
            if username == user.username:
                raise ValidationError(message="该用户已是员工")